package com.elf.zero.utils;

import android.app.Activity;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Window;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * MiUI工具类
 * Created by Lidong on 2018/2/1.
 */
public class MiUIUtils {

    private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
    private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
    private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";

    public static boolean isMiUI(){
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
            return properties.getProperty(KEY_MIUI_VERSION_CODE, null) != null
                    || properties.getProperty(KEY_MIUI_VERSION_NAME, null) != null
                    || properties.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
    }

    /**
     * 是否设置状态栏图标为深色  MIUI V6
     *
     * @param darkMode true 深色
     * @param activity activity
     * @return true设置成功，false设置失败
     */
    public static boolean setStatusBarDarkMode(Activity activity, boolean darkMode) {

        //大于6.0的MIUI状态栏与原生一样
        if((Build.VERSION.SDK_INT > Build.VERSION_CODES.M)) {
            return false;
        }

        //6.0大于等于2017-07-13（1499904000）发布的版本与原生一样处理
        String time = getProperty("ro.miui.version.code_time");
        if (!TextUtils.isEmpty(time)) {
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M && Long.parseLong(time) >= 1499904000L) {
                return false;
            }
        }

        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkMode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
//            e.printStackTrace();
            return false;
        }
    }

    private static String getProperty(String key) {
        try {
            Properties properties = new Properties();
            properties.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
            return properties.getProperty(key, "");
        } catch (Exception e) {
//            e.printStackTrace();
            return "";
        }
    }

}
